﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper;
using CH.FourBoards.LagerWalti.Business.Core;
using CH.FourBoards.LagerWalti.Persistence.Entities;
using CH.FourBoards.LagerWalti.Service.DTOs.MasterData;
using CH.FourBoards.LagerWalti.Service.Mapping;

namespace CH.FourBoards.LagerWalti.Service.MasterData
{
    public class MasterDataService
    {
        public MasterDataService()
        {
            new MasterDataMapper().Register();
        }

        public void AddProduct(ProductDTO newProduct)
        {
            var product = Mapper.Map<Product>(newProduct);
            new ProductManager().AddProduct(product);
        }

        public ProductCatalog ListProducts()
        {
            var ret = new ProductCatalog();
            var products = new ProductManager().ListProducts().ToList();
            ret.Products = products.Select(Mapper.Map<ProductDTO>).ToList();
            ret.Categories = CreateCategorySet(products);
            return ret;
        }

        private ICollection<CategoryDTO> CreateCategorySet(IEnumerable<Product> products)
        {
            var categories = products.Select(p => p.Category).Distinct();
            return categories.Select(Mapper.Map<CategoryDTO>).ToList();
        }

        public IEnumerable<CategoryDTO> ListCategories()
        {
            var categories = new ProductManager().ListCategories();
            return categories.Select(Mapper.Map<CategoryDTO>).ToList();
        }
    }
}
